<?php

/**
 * 文字 / 电话去敏感帮助方法
 */
namespace App\Services\Utils;


class DeSensitive
{
    /**
     * @example
     *   ab@email.com => ab@email.com
     *   abc@email.com => ab*@email.com
     *   abcdefg@email.com => ab***fg@email.com
     *   abcdefghklmnopqrst@email.com => ab***********fg@email.com
     *
     * @param string $email
     *
     * @return string
     */
    public static function asteriskEmail(string $email): string
    {
        $start_char = '(\w{2})';$mid_char = '(.*?)';$end_char='(\w{0,2})';$email_suffix = '(@.*)';

        return preg_replace_callback(
            "/{$start_char}{$mid_char}{$end_char}{$email_suffix}/",
            function (array $matches) {
                $mid_idx = 2;$end_idx = 3;

                if (strlen($matches[$mid_idx])) {
                    $matches[$mid_idx] = str_repeat('*', strlen($matches[$mid_idx]));
                } else {
                    $matches[$end_idx] = str_repeat('*', strlen($matches[$end_idx]));
                }

                unset($matches[0]);
                return implode('', $matches);
            },
            $email
        );
    }

    /**
     * @example
     *   15612349229 => 156****9229
     *   15612349 => 156*9229
     *   156123 => 156123
     *   0086-15612349229 => 008*********9229
     *
     * @param string $phone
     *
     * @return string
     */
    public static function asteriskPhone(string $phone): string
    {
        $start_char = '(\d{3})';$mid_char = '(.*?)';$end_char='(\d{4})$';;

        return preg_replace_callback(
            "/{$start_char}{$mid_char}{$end_char}/",
            function (array $matches) {
                $mid_idx = 2;

                $matches[$mid_idx] = str_repeat('*', strlen($matches[$mid_idx]));

                unset($matches[0]);
                return implode('', $matches);
            },
            $phone
        );
    }

    /**
     * @example
     *   mike bob => m******b
     *   中文名 => 中*名
     *   bob => b**
     *   ab => a*
     *   b => *
     *
     * @param string $name
     * @param int $asterisk_repeat
     *
     * @return string
     */
    public static function asteriskName(string $name, int $asterisk_repeat = null): string
    {
        $len = mb_strlen($name);
        $asterisk = '*';

        if ($len <= 1) {
            return $asterisk;
        } else if ($len === 2) { // mb_substr 处理 char , mb_strcut 处理 byte
            return mb_substr($name, 0, 1) . $asterisk;
        } else {
            return mb_substr($name, 0, 1)
                . str_repeat($asterisk, $asterisk_repeat ?: $len - 2)
                . mb_substr($name, -1);
        }
    }
}